/**
 * 项目名：		DAP 2.0
 * 作  者：			张伟
 * 单  位：			北京超图软件股份有限公司
 * 最后修改时间：		以文件日期为准
 * 功能说明：           	读取cmiss中温度资料的站点数据
 */

package com.mg.cimiss;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public class RestUtilDemo {

    /**
     * REST服务地址，依具体环境设置
     */
    //private final String host = "10.20.76.55";
    //private final String host = "7.223.55.217:8080";//通过VPN临时连接的地址
    private String host = "7.10.69.59:8008";//通过VPN临时连接的地址，，这个是云南的cimiss  云南真实地址10.208.121.20

    /**
     * 请求最长时间
     */
    private final int timeoutInMilliSeconds = 1000 * 60 * 2; // 2 MINUTE

    /**
     * 账户:liying/100081  API:NCC_PGS_SUPERMAP/123456
     */
    //private final String userID = "NCC_PGS_SUPERMAP";
    private String userID = "BEKM_CC_PAMISS";
    /**
     * 密码
     */
    //private final String passWord = "123456";
    private String passWord = "Qhzx123";

    public void setHost(String host_p) {
        host = host_p;
    }

    public void setUserID(String userID_p) {
        userID = userID_p;
    }

    public void setPassWord(String passWord_p) {
        passWord = passWord_p;
    }

    private String errorString = "";

    public String getErrorMessage() {
        return errorString;
    }

    private Map<String, String> m_mapAlias = new HashMap<String, String>();

    /**
     * REST请求服务，获取数据
     */
    public String getRestData(String params) {
        StringBuilder retStr = new StringBuilder();
        URI uri = null;
        URL url = null;
        java.io.BufferedReader reader = null;
        URLConnection con;
        try {

            //ServiceManager.getLogger().debug("发出CIMISS请求:http://" + this.host + "/cimiss-web/api?" + params);

            uri = new URI("http", this.host, "/cimiss-web/api", params, "");
            url = uri.toURL();
            con = url.openConnection();
            con.setConnectTimeout(this.timeoutInMilliSeconds);
            reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line = reader.readLine();
            while (line != null) {
                retStr.append(line).append("\r\n");
                line = reader.readLine();
            }
            reader.close();
        } catch (Exception ex1) {
            ex1.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retStr.toString();
    }

    /**
     * 根据传入的参数获取JSON数组
     *
     * @param params
     * @return
     */
    public JSONArray getRestJsonData(String params) {
        errorString = "";
        String strData = this.getRestData(params);

        try {
            JSONObject json = new JSONObject(strData);
            errorString = json.getString("returnMessage");
            JSONArray results = json.getJSONArray("DS");

            return results;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取查询的Map 结果数组
     *
     * @param params
     * @return
     * @throws JSONException
     */
    public List<Map<String, Object>> getResutMapData(String params) throws JSONException {
        JSONArray jsonArray = this.getRestJsonData(params);

        if (jsonArray == null) {
            return null;
        }
        if (jsonArray.length() < 1) {
            return null;
        }
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject result = jsonArray.getJSONObject(i);
            Map<String, Object> data = new HashMap<String, Object>();
            Iterator it = result.keys();
            while (it.hasNext()) {
                String key = (String) it.next();
                data.put(key, result.get(key));
            }
            dataList.add(data);
        }

        return dataList;
    }

    public List<String> GetResultCSV(String params, Boolean isNeedTime) {
        List<String> listCSV = new ArrayList<String>();
        String strData = this.getRestData(params);

        if (strData.contains("returnMessage")) {
            errorString = "缺失参数";
            return null;
        } else {
            String[] datas = strData.split("\r\n");
            if (datas.length < 2)
                errorString = "没有查询到数据";

            String strDataType = "";
            String fields = datas[0];
            if (!fields.contains("Station_Id_d")) {
                errorString += "CSV格式输出格式查询字段中缺少必要字段Station_Id_d\r\n";
            }
            if (!fields.contains("Lat")) {
                errorString += "CSV格式输出格式查询字段中缺少必要字段Lat\r\n";
            }
            if (!fields.contains("Lon")) {
                errorString += "CSV格式输出格式查询字段中缺少必要字段Lon\r\n";
            }
            if (isNeedTime) {
                if (!fields.contains("Datetime") && !fields.contains("Year")) {
                    errorString += "CSV格式输出格式查询字段中缺少必要字段Datetime\r\n";
                }
            }
            String[] field = fields.split(",");
            int year = -1;
            int month = -1;
            int day = -1;
            int stationIdIndex = -1;
            for (int i = 0; i < field.length; i++) {
                if (field[i].equalsIgnoreCase("Station_Id_d")) {
                    stationIdIndex = i;
                }
                if (field[i].equalsIgnoreCase("Year")) {
                    year = i;
                }
                if (field[i].equalsIgnoreCase("Mon")) {
                    month = i;
                }
                if (field[i].equalsIgnoreCase("Day")) {
                    day = i;
                }
                if (m_mapAlias.containsKey(field[i]) && !field[i].isEmpty())
                    fields = fields.replace(field[i], m_mapAlias.get(field[i]));

                if (field[i].equalsIgnoreCase("StationNum") || field[i].equalsIgnoreCase("Time"))
                    strDataType += "," + "String";
                else
                    strDataType += "," + "Double";
            }
            if (year >= 0 && month >= 0 && day >= 0) {
                fields += "," + "date";
                strDataType += "," + "String";
                if (stationIdIndex >= 0) {
                    fields += "," + "dataId";
                    strDataType += "," + "String";
                }
            }

            if (!errorString.isEmpty())
                return null;
            listCSV.add(fields);
            if (!strDataType.isEmpty())
                strDataType = strDataType.substring(1);
            listCSV.add(strDataType);
            for (int i = 1; i < datas.length; i++)
                listCSV.add(assistData(datas[i], year, month, day, stationIdIndex));
        }
        return listCSV;
    }

    private String assistData(String data, int yearIndex, int monthIndex, int dayIndex, int stationIdIndex) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if (yearIndex >= 0 && monthIndex >= 0 && dayIndex >= 0) {
            int year = Integer.parseInt(data.split(",")[yearIndex]);
            int month = Integer.parseInt(data.split(",")[monthIndex]);
            int day = Integer.parseInt(data.split(",")[dayIndex]);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month - 1);
            calendar.set(Calendar.DAY_OF_MONTH, day);
            data += "," + sdf.format(calendar.getTime());
            if (stationIdIndex >= 0) {
                String dataId = data.split(",")[stationIdIndex];
                data += "," + dataId + sdf.format(calendar.getTime());
            }
        }
        return data;
    }

    /**
     * 根据输入的信息获取对应的查询参数
     *
     * @param interfaceId
     * @param dataCode
     * @param elements
     * @param times
     * @param limits
     * @param paramMap
     * @return
     * @throws Exception
     */
    public String getParams(String interfaceId, String dataCode, String[] elements, String[] times, String adminCodes, String strResStyle, int limits, Map<String, String> paramMap) throws Exception {

        if (interfaceId == null || interfaceId.equals("")) {
            throw new Exception("interfaceId can not be empty");
        }

        if (dataCode == null || dataCode.equals("")) {
            throw new Exception("dataCode can not be empty");
        }

        if (elements == null || elements.length < 1) {
            throw new Exception("elements can not be empty");
        }

        m_mapAlias.clear();
        StringBuilder sb = new StringBuilder();
        sb.append("userId=" + this.userID);
        sb.append("&pwd=" + this.passWord);
        sb.append("&interfaceId=" + interfaceId);
        if (!dataCode.isEmpty())
            sb.append("&dataCode=" + dataCode);
        if (!adminCodes.isEmpty())
            sb.append("&adminCodes=" + adminCodes);
        if (elements != null) {
            String strEle = "";
            sb.append("&elements=");
            for (int i = 0; i < elements.length; i++) {
                strEle = elements[i];
                if (strEle.trim().equals(""))//由于有些字段不是从这个库里取的
                    continue;
                strEle = elements[i].replace(" ", "");
                if (strEle.contains("$as") || strEle.contains("$AS")) {
                    strEle = strEle.replace("$as", ",");
                    strEle = strEle.replace("$AS", ",");
                    String[] strTmp = strEle.split(",");
                    m_mapAlias.put(strTmp[0].trim(), strTmp[1].trim());
                    strEle = strTmp[0];
                }
                sb.append(strEle.trim());
                if (i != elements.length - 1) {
                    sb.append(",");
                }
            }
        }

        if (paramMap != null) {
            for (String key : paramMap.keySet()) {
                sb.append("&key=" + paramMap.get(key).toString());
            }
        }


        if (times != null) {
            if (times.length == 2) {
                sb.append("&timeRange=[" + times[0] + "," + times[1] + "]");
            } else if (times.length == 1) {
                sb.append("&times=" + times[0]);
            }
        }

        if (limits > 0) {
            sb.append("&limitCnt=" + Integer.toString(limits));
        }
        sb.append(String.format("&dataFormat=%s", strResStyle));

        return sb.toString();
    }

    /**
     * 根据输入的信息获取对应的查询参数
     *
     * @param interfaceId
     * @param dataCode
     * @param elements
     * @param limits
     * @param paramMap
     * @return
     * @throws Exception
     */
    public String getParams(String interfaceId, String dataCode, String[] elements, String valueOfYear, String strType, String adminCodes, String strResStyle, int limits, Map<String, String> paramMap) throws Exception {

        if (interfaceId == null || interfaceId.equals("")) {
            throw new Exception("interfaceId can not be empty");
        }

        if (dataCode == null || dataCode.equals("")) {
            throw new Exception("dataCode can not be empty");
        }

        if (elements == null || elements.length < 1) {
            throw new Exception("elements can not be empty");
        }

        m_mapAlias.clear();
        StringBuilder sb = new StringBuilder();
        sb.append("userId=" + this.userID);
        sb.append("&pwd=" + this.passWord);
        sb.append("&interfaceId=" + interfaceId);
        if (!dataCode.isEmpty())
            sb.append("&dataCode=" + dataCode);
        if (!adminCodes.isEmpty())
            sb.append("&adminCodes=" + adminCodes);
        if (elements != null) {
            String strEle = "";
            sb.append("&elements=");
            for (int i = 0; i < elements.length; i++) {
                if (elements[i].trim().equals(""))//由于有些字段不是从这个库里取的
                    continue;
                strEle = elements[i].replace(" ", "");
                if (strEle.contains("$as") || strEle.contains("$AS")) {
                    strEle = strEle.replace("$as", ",");
                    strEle = strEle.replace("$AS", ",");
                    String[] strTmp = strEle.split(",");
                    m_mapAlias.put(strTmp[0].trim(), strTmp[1].trim());
                    strEle = strTmp[0];
                }
                sb.append(strEle.trim());
                if (i != elements.length - 1) {
                    sb.append(",");
                }
            }
        }

        if (paramMap != null) {
            for (String key : paramMap.keySet()) {
                sb.append("&key=" + paramMap.get(key).toString());
            }
        }


        if (strType != null && valueOfYear != null) {
            if (strType.equalsIgnoreCase("Days"))
                sb.append("&daysOfYear=" + valueOfYear);
            else if (strType.equalsIgnoreCase("Tens"))
                sb.append("&tensOfYear=" + valueOfYear);
            else if (strType.equalsIgnoreCase("Mons"))
                sb.append("&monsOfYear=" + valueOfYear);
            else if (strType.equalsIgnoreCase("Pens"))
                sb.append("&pensOfYear=" + valueOfYear);
        }

        if (limits > 0) {
            sb.append("&limitCnt=" + Integer.toString(limits));
        }
        sb.append(String.format("&dataFormat=%s", strResStyle));

        return sb.toString();
    }

    public String getStatParams(String oldParams, String minStatID, String maxStaID, String eleValueRanges, String statEles) {
        String param = oldParams;
        if (!minStatID.equals("") && !maxStaID.equals("")) {
            param += "&minStaId=" + minStatID + "&maxStaId=" + maxStaID;
        }

        if (!eleValueRanges.equals("")) {
            param += "&eleValueRanges=" + eleValueRanges;
        }

        if (!statEles.equals("")) {
            param += "&statEles=" + statEles;
        }

        return param;
    }

    public String getOtherParams(String oldParams, String m_strOtherParams) {
        String param = oldParams;
        String[] arrParam = m_strOtherParams.split("'");
        for (String paramStr : arrParam) {
            param = param + "&" + paramStr;
        }
        return param;
    }
}

